<?php


namespace app\api\controller;

use app\api\logic\SearchRecordLogic;
use app\api\model\ShopSearchRecord;
use think\admin\Controller;

use think\Request;
/**
 * Class Index
 * @package app\api\controller
 */
class Index extends Controller
{
    private $default_type = 'json';
    protected $middleware = ['check'];

    /**
     * GET
     * 首页
     * @return array|string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function index()
    {
        if($this->request->debug != 1){
            $swiperModel = new \app\api\model\DataSwiper();
            $is_show_swiper = 1;
            $swiperList = $swiperModel->getLists(array(
                'status'    => 1
            ),'id,cover as img,new_id,brand_id,good_id,type,sort',[],array(
                'sort'  => 'asc'
            ));
            if(empty($swiperList) === FALSE){
                foreach ($swiperList as &$sv){
//                    $sv['img'] = $sv['img'];
                    if($sv['type'] == 2){
                        //文章  需要将富文本转义
                    }
                }
            }else{
                $is_show_swiper = 0;
            }
            //$brandList  首页显示的品牌
            $is_show_brand = 1;
            $brandModel = new \app\api\model\ShopGoodsBrand();
            $brandList = $brandModel->getLists(array(
                'status'        => 1,
                'is_homeshow'   => 1
            ),'id,cover_icon as img,name,sort,is_homeshow',[],array(
                'sort'  => 'asc'
            ),[0,9]);
            if(empty($brandList)) $is_show_brand = 0;
            //分类商品展示
            $is_show_cate = 1;
            $categoryModel = new \app\api\model\ShopGoodsCate();
            $categoryList = $categoryModel->getLists(array(
                'status'        => 1,
                'is_homeshow'   => 1,
                'level'         => 1
            ),'name,cover as img,id','',array(
                'sort'  => 'asc'
            ),[0,8]);
            if(empty($categoryList) === FALSE){
                foreach($categoryList as &$cv){
                    $cv['productList'] = \Common::getCategoryGoods($cv['id'],1);
                }
            }else{
                $is_show_cate = 0;
            }
            //获取未读消息数量
            //获取购物车中商品数量
            $common_cart_total = 0;
            $tokeninfo = $this->request->tokeninfo;
            if(empty($tokeninfo) === FALSE){
                $shopCartModel = new \app\api\model\ShopCart();
                $shopCartnum = $shopCartModel->getSum(array(
                    'user_id'   => $tokeninfo['id']
                ),'goods_num');
                $common_cart_total = $shopCartnum;
            }
            //获取是否开通vip模块
            //获取数据为空时  提示内容
            $can_open_vip = sysconf("can_open_vip");
            if(!isset($can_open_vip)) $can_open_vip = 0;
            $null_tips = sysconf("null_tips");
            if(!isset($null_tips)) $null_tips = '此书在仓库，暂未上架，请联系客服，微信添加朋友→企业微信联系人:13260236583';
            $result = array(
                'is_show_swiper'        => $is_show_swiper,//是否显示轮播
                'swiperList'            => $swiperList,//轮播内容
                'is_show_brand'         => $is_show_brand,//是否显示品牌
                'brandList'             => $brandList,//品牌内容
                'is_show_cate'          => $is_show_cate,//是否显示分类
                'categoryList'          => $categoryList,//分类内容
                'common_cart_total'     => $common_cart_total,//购物车数量
                'common_message_total'  => 0,//消息数量
                'can_open_vip'  => $can_open_vip,//消息数量
                'null_tips'  => $null_tips,//消息数量
            );
            return \Tools::returnMsg(true,$result,$this->default_type);
        }
    }
        /**
     * 获取分享二维码加密串
     * @return array|string
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function getShareCode(){
        if($this->request->debug != 1) {
            $tokeninfo = $this->request->tokeninfo;
            if (empty($tokeninfo)) {
                return \Tools::returnMsg(false, array(
                    'code' => '100001',
                    'message' => '未登录'
                ), $this->default_type);
            }
            $id = input('id','','trim,intval');//商品id
            if(empty($id)){
                return \Tools::returnMsg(false,array(
                    'code'      => '10008',
                    'message'   =>'参数不能为空 '
                ),$this->default_type);
            }
            $goodsModel = new \app\api\model\ShopGoods();
            $goodsinfo = $goodsModel->getOne(array(
                'id'    => $id
            ),'id,cover,name,price_selling');
            if(empty($goodsinfo)){
                return \Tools::returnMsg(false,array(
                    'code'      => '10004',
                    'message'   =>'参数有误 '
                ),$this->default_type);
            }
            $data = array(
                'uuid'    =>$tokeninfo['id'],
                'goods_id'=>$id
            );
            $file_path = \Common::createQrcode($data);
            //上传结束
            $t = strpos($goodsinfo['cover'],'https');
            if(!$t && !is_numeric($t)){
                $goodsinfo['cover'] = str_replace('http','https',$goodsinfo['cover']);
            }
            return \Tools::returnMsg(true,array(
                'cover' => $goodsinfo['cover'],
                'name'  => $goodsinfo['name'],
                'price' => $goodsinfo['price_selling'],
                'qrcode'=> $file_path
            ),$this->default_type);
        }
    }
        /**
     * 获取分享短链接
     * @return array|string
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function getShortUrlLink(){
        $tokeninfo = $this->request->tokeninfo;
        if (empty($tokeninfo)) {
            return \Tools::returnMsg(false, array(
                'code' => '100001',
                'message' => '未登录'
            ), $this->default_type);
        }
        $id = input('id','','trim,intval');//商品id
        if(empty($id)){
            return \Tools::returnMsg(false,array(
                'code'      => '10008',
                'message'   =>'参数不能为空 '
            ),$this->default_type);
        }
        $goodsModel = new \app\api\model\ShopGoods();
        $goodsinfo = $goodsModel->getOne(array(
            'id'    => $id
        ),'id,cover,name,price_selling');
        if(empty($goodsinfo)){
            return \Tools::returnMsg(false,array(
                'code'      => '10004',
                'message'   =>'参数有误 '
            ),$this->default_type);
        }
        //生成二维码
        $appid = sysconf('wx_appid');
        $secret = sysconf('wx_secret');
        $object = new \Wxchat($appid,$secret);
        $accessToken = $object->getaccesstoken();
        $userModel = new \app\api\model\DataUser();
        $userinfo = $userModel->getOne(
            array(
                'id'=> $tokeninfo['id']
            ),'distribution_code');
        $path = 'pagesB/goods/goods?share_user_code=' . $userinfo['distribution_code'].'&id='.$id;
        $res = $object->createshortLink($accessToken, $path,$goodsinfo['name'],true);
        if($res['code'] == 0){
            return \Tools::returnMsg(true,array(
                'link'  => \Tools::unicode2utf8($res['data'])
            ),$this->default_type);
        }else{
            return \Tools::returnMsg(false,array(
                'code'      => '10004',
                'message'   =>'参数有误 '
            ),$this->default_type);
        }
    }

    /**
     * 用户历史搜索记录
     */
    public function searchGoods()
    {
        $headers = \Tools::get_all_header();
        $tokeninfo = [];
        if(isset($headers['accesstoken']) && empty($headers['accesstoken']) === FALSE) {
            $tokeninfo = \Tools::checkJWTToken($headers['accesstoken']);
        }
        if(empty($tokeninfo) === FALSE){
            $lists = SearchRecordLogic::lists($tokeninfo['id']);
        }else{
            $lists = [];
        }

        return \Tools::returnMsg(true,$lists,$this->default_type);
    }

    /**
     * 清空用户搜索历史
     */
    public function clearSearchGoods()
    {
        if($this->request->isPost()) {
            $tokeninfo = $this->request->tokeninfo;
            if(empty($tokeninfo) === FALSE){
                $result = SearchRecordLogic::clear($tokeninfo['id']);
            }else{
                $result = true;
            }

            if($result) {
                return \Tools::returnMsg(true,[],$this->default_type);
            }
            return \Tools::returnMsg(false, array(
                'code' => '100001',
                'message' => '类型有误'
            ), $this->default_type);
        }else{
            return \Tools::returnMsg(false, array(
                'code' => '100001',
                'message' => '类型有误'
            ), $this->default_type);
        }
    }
}
